require("./index.scss");
var FileUpload = require("COMMON/modules/fileupload");
var ProvCitySelector = require("COMMON/Components/ProvCitySelect/v1.0/");
var Pagination = require("COMMON/modules/pagination-x/v1.0/");
var ParseTemplate = ZFT.Util.ParseTemplate;
var Select = require("COMMON/modules/select/index.1.0");
var ImgUploador = require("../../mem");
var STip = ZFT.Util.STip;
var Ajax = ZFT.Util.Ajax;
var Template = {
    baseDom: ParseTemplate(require("../tpl/addcontract_base.xtpl")),
    select: ParseTemplate(require("../tpl/select.xtpl")),
    ctList: ParseTemplate(require("../tpl/getbdlist_add.xtpl")),
    addCt: ParseTemplate(require("../tpl/addcontract_add.xtpl")),
    feeTr: ParseTemplate(require("../tpl/feelist_tr_add.xtpl")),
    addleaseimg: ParseTemplate(require("../tpl/addleaseimg.xtpl")),
    growthrateinp: ParseTemplate(require("../tpl/growthratebinp.xtpl")),
    userinfo: ParseTemplate(require("../tpl/addcontract_add_userinfo.xtpl")),
    adduser: ParseTemplate(require("../tpl/addcontract_add_newuser.xtpl")),
    nomatch: ParseTemplate(require("../tpl/addcontract_add_nomacth.xtpl"))
};
var Main = ZFT.Util.Class({
    container: $("body"),

    init: function () {
        var _this = this,
            baseDom;

    
            var data,
                pers=_this.pers = ZFT.Util.getPermission();
            data = {
                addBtn: ($.inArray("27", pers) !== -1) ? 1 : 0
            }
            baseDom = Template.baseDom({ data: data });
            $("#baseContent").html(baseDom);


            //省市区三级联动
            _this.getContractList(1);//获取合同列表
            _this.locationSelect = new ProvCitySelector({
                provId: '#schProQy',                    //参数为<select></select>省标签的id
                cityId: '#schCityQy',                        //参数为<select></select>市标签的id
                onProvChange: function (provId) {
                    var areaSelect = $("#schAreaQy");
                    var option = '<option value="0">请选择</option>';
                    areaSelect.show().html(option);                //当省下拉框变化时执行的回调函数，参数为 省下拉框中 所选省份对应的省份代号
                },
                onCityChange: function (cityId) {                    //当省下拉框变化时执行的回调函数，参数为 市下拉框中 所选城市对应的城市代号
                    _this.ajaxRenderDistrict(cityId);
                },
                afterLoading: function () {
                    _this.ajaxRenderDistrict($('#schCityQy').val());
                }
            });


        //初始化分页
        var pagination = _this.pagination = new Pagination({
            container: $(".paginationWrap"),
            count: 5,
            showTotal: true,
            jump: true,
            filter: true
        })
        pagination.on("page.switch", function (toPage, currentPage, totalPage) {
            pagination.render({ current: currentPage, toPage: toPage }),
                _this.getContractList(toPage);
        });

        //搜索合同房源列表
        $("#schCtBtn").on("click", function () {
            _this.getContractList(1);
        })

    },
    EVENTS: {
        "click #addContract": "addContract",
        "click .cancel,.close": "closeModal",
        "click .del-btn": "onClickImgDivDelbtn",

    },
    //选中radio
    /* radioCheck: function (e) {
         var _this = $(e.currentTarget);
         _this.find("input[type=radio]").prop("checked", "checked");
     },*/

    //初始化图片上传插件
    initImgUpload: function (i) {
        var uploadorname = $("#imgLoaderContainer_" + i).find("input[name=callback]").val();
        if (uploadorname) {
            uploadorname = uploadorname.split(".")[0];
            window[uploadorname] = new ImgUploador({ container: $("#imgLoaderContainer_" + i) });
        }
    },
    //获取区域地址
    ajaxRenderDistrict: function (cityId) {
        var areaSelect = $("#schAreaQy");
        if (!cityId) {
            areaSelect.html('<option value="0">请选择</option>');
            return false;
        }
        var _this = this;
        Ajax(
            '/index/getCountry.html',
            {
                type: 'POST',
                params: {
                    city_id: cityId
                },
                success: function (res) {
                    var html = '<option value="0">请选择</option>';
                    if (res.code == 200) {
                        html += Template.select({ data: res.data.list });
                        areaSelect.html(html);
                    } else {
                        areaSelect.hide()
                    }
                },
                serverError: function (xhr, txt) {

                }
            }

        )
    },
    //绑定用户性质变化时营业执照和法人身份证信息的变化   暂弃
    onZtypeChange: function () {
        $("#ztype").on("change", function (e) {
            var tarOp = $(e.currentTarget);
            var tarV = tarOp.val()
            $("#cropInfoBox").css("display", (tarV == 0) ? "none" : "inline-block").find(".m-form_control").val("");
            $("#idBox").css("display", (tarV == 1) ? "none" : "inline-block");
        })
    },
    //初始化日历插件
    initDatepicker: function () {
        $("#beginDate").datepicker({
            format: "yyyy-mm-dd",
            maxViewMode: 2,
            language: "zh-CN",
            autoclose: true
        });
        $('#endDate').datepicker({
            format: "yyyy-mm-dd",
            maxViewMode: 2,
            language: "zh-CN",
            autoclose: true
        });
        $('#contractTime').datepicker({
            format: "yyyy-mm-dd",
            maxViewMode: 2,
            language: "zh-CN",
            autoclose: true
        });

        /*$("#billing_day").datepicker({
            format: "mmdd",
            startView: 1,
            maxViewMode: 1,
            language: "zh-CN",
            autoclose: true
        });*/
    },

    //检测租赁时间间隔
    checkDate: function () {
        var _this = this;
        $("#beginDate,#endDate,#freeDay").on("change", function (e) {
            var tarInp = $(e.currentTarget);
            var beginDate = $("#beginDate").val();
            var endDate = $("#endDate").val();
            var freeDay = $("#freeDay").val();
            var fmBeginDate = new Date(beginDate.replace(/-/g, '/')).getTime() / 1000;
            var fmEndDate = new Date(endDate.replace(/-/g, '/')).getTime() / 1000;
            var newFmBeginDate = new Date((fmBeginDate) * 1000);
            var newFmEndDate = new Date((fmEndDate) * 1000);
            var beginY = newFmBeginDate.getFullYear();
            var endY = newFmEndDate.getFullYear();
            var beginM = newFmBeginDate.getMonth() + 1;
            var endM = newFmEndDate.getMonth() + 1;
            var beginD = newFmBeginDate.getDate();
            var endD = newFmEndDate.getDate();
            var compareY = endY - beginY;

            // console.log( newFmBeginDate.toLocaleDateString(), newFmEndDate.toLocaleDateString());
            if (!freeDay) tarInp.val(0);
            if (!beginDate || !endDate) return false;
            if (fmBeginDate > fmEndDate) {
                tarInp.val("");
                return STip("fail", "退租时间不能早于起租时间!", 5000);
            }
            if (parseInt(fmEndDate) - parseInt(fmBeginDate) > 315532800) {
                console.log(parseInt(endDate.replace(/-/g, '')) - parseInt(beginDate.replace(/-/g, '')))
                return STip("fail", "租赁时间不超过10年!", 5000);
            }
            if (newFmBeginDate < newFmEndDate) {
                if (beginM == endM) {
                    if (beginD <= endD) {
                        _this.createGroRateBox(compareY + 1);
                    } else {
                        _this.createGroRateBox(compareY);
                    }
                } else if (beginM > endM) {
                    _this.createGroRateBox(compareY);
                } else {
                    _this.createGroRateBox(compareY + 1);
                }
            } else {
                _this.createGroRateBox(1);
            }

        });

    },
    //监听租金账单日和免租期
    listenBillInp: function (inpId, chk) {
        //chk: 1 租金账单日 2 免租期 
        $(inpId).on("input propertychange", function (e) {
            var $tarInp = $(e.currentTarget);
            var $tarVal = $tarInp.val();
            var exp = /^[0-9]\d*$/; //租金账单日和免租期的监听
            //var expr = /^(\d*\.)?\d+$/;
            var exps = /^(?!0+(\.0+)?$)\d+(\.\d+)?$/;
            if (chk == 1) {
                if (exp.test($tarVal)) {
                    if ($tarVal > 29) {
                        return $tarInp.val(28);
                    } else if ($tarVal == 0) {
                        return $tarInp.val("");
                    }
                } else {
                    return $tarInp.val("");
                }

            } else if (chk == 2) {
                if (!exp.test($tarVal)) {
                    return $tarInp.val("");
                }
            }
        })
    },
    //
    //生成增长率input框
    createGroRateBox: function (len) {
        var html;
        if (len - 1 < 0) return false;
        html = Template.growthrateinp({ data: len });
        $("#growthRateBox").html(html);
    },
    //获取合同列表
    getContractList: function (page) {
        var that = this;
        var schAreaQy = $("#schAreaQy");
        var areaTxt = (schAreaQy.val() == "0") ? schAreaQy.val() : $("#schAreaQy option:selected").text();
        var tbody = $("#tbodyAddct");
        var pagination = $(".paginationWrap");
        $("#schAreaQy option:selected").attr("value", areaTxt);
        var dataForm = $("#contractParam").serialize();
        var pageSize = pagination.attr("data-size");
        if (!page) page = 1;
        var data = $.param({ 'page': page, 'page_size': pageSize ? pageSize : 10 }) + '&' + dataForm;
        Ajax(
            '/r/building_getLeaseHouse',
            {
                type: "POST",
                dataType: "json",
                params: data,
                loading: function () {
                    pagination.hide();
                    var loading = "<tr><td colspan='8'>正在加载,请稍后...</td></tr>"
                    tbody.html(loading);
                },
                success: function (res) {
                    var data = res.data.list;
                    var area = "";

                    if (res.code == 200) {
                        if (!data) {
                            pagination.hide();
                            tbody.html('<tr><td colspan="8">暂无数据</td></tr>');
                            return false;
                        } else {
                            var html ;
                            for (var i = 0, len = data.length; i < len; i++) {
                                data[i].city = that.locationSelect.getCity(data[i].province, data[i].city);
                                data[i].province = that.locationSelect.getProvince(data[i].province);
                            }
                            data["ctPer"]=($.inArray("27", that.pers) !== -1) ? 1 : 0;
                             html = Template.ctList({ data: data }, that);
                            tbody.html(html);
                            that.pagination.render({ current: page, toPage: page, total: res.data.totalpage });
                        }
                    } else if (res.code == 102) {
                        tbody.html('<tr><td colspan="8"><a href="/index/index/login">' + res.msg + '</td></tr>');
                    } else {
                        tbody.html('<tr><td colspan="8">' + res.msg + '</td></tr>');
                    }
                }
            }

        )
    },
    addContract: function () {
        var _this = this;
        var fyTableInp = $("#fyTable .u-inp_feeTd:checked");
        var building_id = fyTableInp.eq(0).attr("data-buildingId");
        var houseId = fyTableInp.val();
        var param;
        var arr = [];
        var newArr = [];
        if (!houseId) return STip("fail", "请至少选中一个房源签约!");

        for (var i = 0, len = fyTableInp.length; i < len; i++) {
            var ctId = fyTableInp.eq(i).val();
            var room = fyTableInp.eq(i).attr("data-room");
            var name = fyTableInp.eq(i).attr("data-houseName");
            var buidingId = fyTableInp.eq(i).attr("data-buidingId");
            arr.push(ctId);
            newArr.push({ id: ctId, room: room, name: name });

        }
        param = {
            houseId: JSON.stringify(arr),
            building_id: building_id
        }
        //console.log(arr, newArr,param[0]["buildingId"]);
        Ajax("/r/Lease_checkHouseLegal", {
            type: "POST",
            dataType: "json",
            params: {
                house_number: JSON.stringify(arr)
            },
            success: function (res) {
                if (res.code == 200) {
                    _this.initAddCtModal(param, newArr);

                } else {
                    return STip("fail", res.msg, 5000);
                }
            },
            error: function () {
                STip("fail", "加载失败!请刷新页面重试!", 5000);
            }
        })

    },
    //初始化租赁签约模态框
    initAddCtModal: function (param, arr) {
        var _this = this;
        var ctContent = $("#ctContent");
        Ajax(
            "/r/Lease_findHouseInfo",
            {
                type: "POST",
                dataType: "json",
                params: param,
                success: function (res) {
                    var tbody = $("#tbody");
                    var data = res;
                    if (res.code == 200) {
                        var html;
                        data["houseArr"] = arr;
                        //console.log(data)

                        html = Template.addCt({ data: data });
                        ctContent.html(html).show(1000);

                        _this.initName();

                        _this.toggleName();
                        _this.checkFeeObj();
                        _this.initDatepicker();//初始化日历
                        //  _this.checkFeeCharge();
                        _this.listenInp();
                        _this.creatFeeList(param.houseId, param.building_id);
                        _this.initImgUpload("i1"); //初始化图片上传
                        _this.initImgUpload("i2");
                        _this.initImgUpload("1");
                        _this.clickAddImgDiv();
                        _this.checkDate();//初始化日历检测
                        // _this.onZtypeChange();//绑定用户类型变化事件
                        _this.listenBillInp("#billing_day", 1);//监听租金账单日
                        _this.listenBillInp("#freeDay", 2);//监听免租期
                        _this.checkTaxToEnableTaxInp();//监听收税状态解除input的禁用
                    } else if (res.code == 102) {
                        return STip("fail", "未登录,请重新登录", 4000, function () {
                            window.location.href = "/index/index/login";
                        });
                    } else {
                        return STip("fail", res.msg, 4000);
                    }

                }

            })
    },
    //选中收费对象的时候生成对应收费比例输入框
    checkFeeObj: function () {
        var _this = this;
        var feeObj = $("#tbody .feelabel");
        feeObj.on("change", ".feeObj", function (e) {
            var that = $(e.currentTarget);
            var dataId = that.attr("data-id"); // "收费对象 0 超管，1 业主， 2租户, 3托管公司, 4运营方, 5物业公司, 6水电公司"
            //  console.log(dataId)
            _this.creatRationInp(dataId, that);
        })

    },
    //生成收费比例输入框
    creatRationInp: function (dataId, target) {
        //console.log(dataId, target,target.prop("checked"));
        if (target.prop("checked")) {
            target.parents(".objTd").siblings(".ratioTd").find("input[data-id=" + dataId + "]").show();
        } else {
            target.parents(".objTd").siblings(".ratioTd").find("input[data-id=" + dataId + "]").hide().val('');
        }
    },
    //生成收费明细列表
    creatFeeList: function (houseId, buildingId) {
        var _this = this;
        var addBtn = $("#add");
        var saveBtn = $("#saveBtn");
        var addFeeList = $("#addFeeList");
        addBtn.off("click");
        saveBtn.off("click");
        addBtn.on("click", function () {
            var feeChkBox = $("#tbody .feeTd :checkbox:checked");
            var feeInfo = [];
            if (feeChkBox.length < 1) return STip("fail", "请至少选中一个收费项目!");
            for (var i = 0, len = feeChkBox.length; i < len; i++) {
                var objChkBox = feeChkBox.eq(i).parent().siblings(".objTd").find(':checkbox:checked');
                var feeTr = feeChkBox.eq(i).parent().parent();
                var fee = feeTr.attr("data-money");
                var feeType = feeTr.attr("data-type");
                var ratioInp = feeChkBox.eq(i).parent().siblings(".ratioTd").find("input:visible");
                var ratio = 0;

                if (objChkBox.length < 1) return STip("fail", "请至少选择一个收费对象!");

                for (var j = 0, leng = ratioInp.length; j < leng; j++) {
                    var ratioInpVal = ratioInp.eq(j).val();
                    var feeObjCt = ratioInp.eq(j).attr("data-info"); //缴费对象账号
                    var feeObjId = ratioInp.eq(j).attr("data-id"); //缴费对象账号
                    if (!ratioInpVal) return STip("fail", "比例不能为空!")
                    ratio = ratio + parseInt(ratioInpVal);
                    feeInfo.push({ "fee": fee, "owner_id": feeObjCt, "type": feeType, "ratio": ratioInpVal, "objType": feeObjId });
                }
                if (parseInt(ratio) != 100) {
                    return STip("fail", "费用比例相加必须为100!");
                }
            }

            var html = Template.feeTr({ data: feeInfo });
            addFeeList.html(html);
            saveBtn.on("click", function () {

                _this.saveFeeList(feeInfo, houseId, buildingId);
            })
        })

    },

    //遍历生成折扣率数组
    /*    createDiscountList: function () {
            var arr = [];
            var regx = /^(\d*\.)?\d+$/;
            var $rateInp = $("#growthRateBox .rateInp");
            for (var i = 0; i < $rateInp.length; i++) {
                var $val = $rateInp.eq(i).val();
                if (!regx.test($val)) {
                    $rateInp.eq(i).val(0)
                    return STip("fail", "请输入第" + (i + 2) + "年增长率,小数点保留2位!", 5000);
                }
                if ($val > 10) return STip("fail", "折扣率控制在10%以内!", 5000);
                arr.push(parseFloat($val).toFixed(2))
                //console.log($val);
            }
            return arr;
        },*/
    //勾选是否收税来解除对应项目以及税点的只读
    checkTaxToEnableTaxInp: function () {
        var taxProj = "#taxProj";
        var tax = "#tax";
        $("#ifTax").on("change", function (e) {
            var $tar = $(e.currentTarget);
            if ($tar.prop("checked")) {
                $(taxProj + "," + tax).removeAttr("disabled", "disabled");
            } else {
                $(taxProj + "," + tax).attr("disabled", "disabled");
            }
        })
    },
    //遍历生成水电读数数组
    /* createMeterList: function () {
         var arr = [];
         var regx = /^(\d*\.)?\d+$/;
         var $waterMeterInp = $("#meterList .water_meter");
         var $elecMeterInp = $("#meterList .electric_meter");
         for (var i = 0; i < $elecMeterInp.length; i++) {
             var $wVal = $waterMeterInp.eq(i).val();
             var $eVal = $elecMeterInp.eq(i).val();
             var $room = $elecMeterInp.eq(i).attr("data-room");
             var $hnum = $elecMeterInp.eq(i).attr("data-hnum");
             if (!regx.test($eVal)) {
                 $elecMeterInp.eq(i).val("").focus();
                 STip("fail", "请输入房号" + $room + "正确的电表读数,保留2位小数!", 5000)
                 return false;
             }
             if (!regx.test($wVal)) {
                 $waterMeterInp.eq(i).val("").focus();
                 STip("fail", "请输入房号" + $room + "正确的水表读数,保留2位小数!", 5000)
                 return false;
             }
 
             arr.push({ house_number: $hnum, water: parseFloat($wVal).toFixed(2), power: parseFloat($eVal).toFixed(2) });
         }
         return arr;
     },*/

    //保存收费项目
    saveFeeList: function (feeInfo, houseId, buidingId) {
        var _this = this;
        var ctContent = $("#ctContent");
        var saveBtn = $("#saveBtn");
        var beginDate = $("#beginDate").val();
        var endDate = $("#endDate").val();
        /*var fmBeginDate = new Date(beginDate.replace(/-/g, '/')).getTime() / 1000;
        var fmEndDate = new Date(endDate.replace(/-/g, '/')).getTime() / 1000;*/
        var fmBeginDate = beginDate.replace(/-/g, '');
        var fmEndDate = endDate.replace(/-/g, '');
        var charge_type = $("#charge_type").val();
        var billing_day = $("#billing_day").val();
        var photo = _this.formatImgSrcToString();
        var discount = $("#discountInp").val();
        //var meter = JSON.stringify(_this.createMeterList());
        // var growth_rate = JSON.stringify(_this.createDiscountList());
        var tax = $("#tax").val();
        //生成折扣率数组
        var rateArr = [];
        var regx = /^(\d*\.)?\d+$/;
        var regTime = /^\d+$/;
        var regTel = /^1\d{10}$/;
        var $rateInp = $("#growthRateBox .rateInp");
        //生成水电读数数组
        var meterArr = [];
        var $waterMeterInp = $("#meterList .water_meter");
        var $elecMeterInp = $("#meterList .electric_meter");
        var contractTime = $("#contractTime").val().replace(/-/g, '');
        if (beginDate > endDate) return STip("fail", "退租时间不能早于起租时间!");
        /*if (parseInt(fmEndDate) - parseInt(fmBeginDate) > 315532800) {
            return STip("fail", "租赁时间不超过10年!", 5000);
        }*/
        if (parseInt(fmEndDate) - parseInt(fmBeginDate) > 100000) {

            return STip("fail", "租赁时间不超过10年!", 5000);
        }
        if (!regTime.test(contractTime)) return STip("fail", "请选择租赁时间！");
        for (var i = 0; i < $rateInp.length; i++) {
            var $val = $rateInp.eq(i).val();
            /*if (!regx.test($val)) {
                $rateInp.eq(i).val(0)
                return STip("fail", "请输入第" + (i + 2) + "年增长率,小数点保留2位!", 5000);
            }*/
            //    if ($val > 10) return STip("fail", "折扣率控制在10以内!", 5000);
            rateArr.push(parseFloat($val).toFixed(2))
            //console.log($val);
        }

        for (var i = 0; i < $elecMeterInp.length; i++) {
            var $wVal = $waterMeterInp.eq(i).val();
            var $eVal = $elecMeterInp.eq(i).val();
            var $room = $elecMeterInp.eq(i).attr("data-room");
            var $hnum = $elecMeterInp.eq(i).attr("data-hnum");
            if (!regx.test($eVal)) {
                $elecMeterInp.eq(i).val("").focus();
                STip("fail", "请输入房号" + $room + "正确的电表读数,保留2位小数!", 5000)
                return false;
            }
            if (!regx.test($wVal)) {
                $waterMeterInp.eq(i).val("").focus();
                STip("fail", "请输入房号" + $room + "正确的水表读数,保留2位小数!", 5000)
                return false;
            }

            meterArr.push({ house_number: $hnum, water: parseFloat($wVal).toFixed(2), power: parseFloat($eVal).toFixed(2) });
        }
        //  console.log(feeinfo);
        var params = {
            industry: $("#industry").val(),
            ztype: $("#ztype").val(),
            building_id: buidingId,
            house_number: houseId,
            sex: $("#addContractForm input[name='sex']:checked").val(),
            mobile: $("#mobile").val(),
            id_card: $("#id_card").val(),
            begin_time: fmBeginDate,
            end_time: fmEndDate,
            charge_type: charge_type,
            billing_day: billing_day,
            id_card_a: $("#id_card_hand_hid_inp").val(),
            id_card_b: $("#id_card_B_hid_inp").val(),
            feeInfo: JSON.stringify(feeInfo),
            photo: photo ? photo : "",
            meter: JSON.stringify(meterArr),
            growth_rate: (rateArr.length > 0) ? JSON.stringify(rateArr) : "",
            free_day: $("#freeDay").val(),
            finance_mobile: $("#financeTel").val(),
            finance_user: $("#financeUser").val(),
            contract_time: contractTime,
            use_billing_day: ($("#isBillDay").is(":checked")) ? 1 : 0,
            tenant_id: $("#tenant_name").attr("data-id"),
        }

        if ($("#ifTax").prop("checked") && tax) {
            var regxx = /^[0]+/;
            var taxx;
            if (regx.test(tax)) {
                if (tax > 100) {
                    return STip("fail", "税点值在0~100之间!");
                }
            } else {
                return STip("fail", "税点值在0~100之间!");
            }
            params["tax"] = tax.replace(regxx, "");
        } else if ($("#ifTax").prop("checked") && !tax) {
            return STip("fail", "确定收税后,税点不为空!");
        }

        if (discount && regx.test(discount)) {
            if (regx > 10) return STip("fail", "房租折扣应在0.1~10之间!");
            params["discount"] = parseFloat(discount).toFixed(2);
        }
        if (params["ztype"] == 1) {
            var tname = $("#tenant_name").val();
            var license = $("#license").val();
            params["legal_id_card"] = $("#legalIdCard").val();
            if (!license) return STip("fail", "营业执照不为空!");
            if (!tname) return STip("fail", "企业名称不为空!");
        } else {
            var tname = $("#tenant_name").val();
            if (!tname) return STip("fail", "姓名不为空!");
        }
        if (!regTel.test(params["finance_mobile"])) return STip("fail", "请输入财务联系人电话!");
        if (!params["finance_user"]) return STip("fail", "财务联系人姓名不为空!");

        // console.log(params)
        Ajax(
            '/r/Lease_insertContractInfo',
            {
                type: "POST",
                dataType: "json",
                params: params,
                loading: function () {
                    saveBtn.attr("disabled", "disabled").removeClass("m-btn_primary");
                },
                success: function (res) {
                    if (res.code == 200) {
                        ctContent.hide().html('');
                        STip("success", res.msg, 4000);
                        _this.getContractList(1);
                    } else if (res.code == 102) {
                        return STip("fail", "未登录,请重新登录", 4000, function () {
                            window.location.href = "/index/index/login";
                        });
                    } else {
                        saveBtn.removeAttr("disabled").addClass("m-btn_primary");
                        return STip("fail", res.msg);
                    }

                }
            })
    },
    //监听input,输入的值只能为不大于100的整数
    listenInp: function () {

        $("#tbody input[type='text']").bind("input propertychange", function () {
            var $_this = $(this);
            var val = $_this.val();
            var exp = /^[0-9]\d*$/;
            if (exp.test(val)) {
                if (val > 100) {
                    $_this.val(100);
                    return false;
                } else if (val == 0 && val.length > 1) {
                    $_this.val(0);
                    return false;
                } else if (val.length > 1 && val.indexOf("0") == 0) {
                    var reg = /0/g;
                    var Val = val.replace(reg, "");
                    $_this.val(Val)
                }
            } else {
                $_this.val('');
                return false
            }

            //console.log(val)
        })
    },
    //检测收费周期
    checkFeeCharge: function () {
        $("#charge_type").on("change", function (e) {
            $("#billing_day").datepicker('destroy')
            var type = $(e.currentTarget).val();
            //console.log(type)
            if (type == 1) {
                $("#billing_day").datepicker({
                    format: "mmdd",
                    startView: 1,
                    maxViewMode: 1,
                    language: "zh-CN",
                    autoclose: true
                }).val("");
            } else {
                $("#billing_day").datepicker({
                    format: "dd",
                    maxViewMode: 0,
                    language: "zh-CN",
                    autoclose: true
                }).val("");
            }
        })
    },
    //关闭模态框
    closeModal: function (e) {
        var tarBtn = $(e.currentTarget);
        tarBtn.parents(".m-modal_bg").fadeOut(200);
    },
    //点击图片添加按钮
    clickAddImgDiv: function (e) {
        var _this = this;
        var i = 1;
        var addImgDivId = "#addLeaseImgDiv";
        var addImgDiv;
        $(addImgDivId).on("click", function (e) {
            i++;
            var tarBtn = $(e.currentTarget);
            addImgDiv = Template.addleaseimg({ i: i });
            tarBtn.parents(".fbox.lt").before(addImgDiv);
            _this.initImgUpload(i);
        })
    },
    //删除当前图片上传的容器
    onClickImgDivDelbtn: function (e) {
        var tarBtn = $(e.currentTarget);
        tarBtn.parents(".lt").hide(200, function () {
            tarBtn.parents(".lt").remove();
        });
    },
    //遍历图片地址为字符串
    formatImgSrcToString: function () {
        var imgUrl;
        var array = [];
        $.each($("#leaseUploadBox  .hidInp_imgurl"), function (i, url) {
            if ($(url).val()) {
                array.push($(url).val());
            }
        })
        imgUrl = array.join(",");
        return imgUrl;
    },
    //初始化姓名
    initName: function () {
        var _this = this;
        var select = new Select({
            source: "/r/Lease_searchTenant",
            ajaxType: "POST",
            ajaxParams: {

            },
            isFillContent: false,
            filterType: "ajax",  //指定过滤方式为ajax
            field: {
                id: "id",
                name: "title",
                keyword: "name"
            },
            trigger: $("#tenant_name"),
            filter: true,
            adaptor: function (res) {
                var tenant_name = $("#tenant_name")
                var reslut = { code: 200 };
                var list = res.data;
                var addUserBox = $("#addUserBox")
                if (!list) {
                    return reslut;
                }
                var newList = [];
                for (var i = 0; i < list.length; i++) {
                    list[i].id = list[i].id;
                    list[i].title = list[i].nickname
                    newList.push(list[i]);
                }
                reslut["data"] = newList;
                if (list.length > 0) {
                    addUserBox.html("");
                    tenant_name.attr({ "data-id": list[0].id, "data-title": list[0].title })/*.val(list[0].title)*/;
                    //_this.toggleInfoFromName();
                } else {
                    var nomatch = Template.nomatch();
                    tenant_name.val("");
                    addUserBox.html(nomatch);
                    _this.addUser();
                }

                return reslut;
            },
        })
    },
    //选择名字
    toggleName: function () {
        var _this = this;
        $(".gSelectDownBox").on("click", "li", function () {
            _this.toggleInfoFromName();
        })
    },
    //根据用户姓名搜索 更换相应资料
    toggleInfoFromName: function () {
        var id = $("#tenant_name").attr("data-id");
        var infoBox = $("#infoBox");
        Ajax("/r/Lease_searchTenantById", {
            type: "POST",
            dataType: "json",
            params: {
                id: id
            },
            success: function (res) {
                if (res.code == 200) {
                    var html = Template.userinfo({ data: res.data });
                    infoBox.html(html);
                } else {
                    STip("fail", res.msg);
                }
            }
        })
    },
    //新增用户
    addUser: function () {
        var html = Template.adduser();
        var infoBox = $("#infoBox");
        var regTel = /^1\d{10}$/;
        $("#addNewUserBtn").on("click", function () {
            infoBox.html(html);
            setTimeout(function () {
                $("#tenantName,#addNewPwd").val("").css("background-color", "#fff");;
                $("input:-webkit-autofill").css("-webkit-box-shadow", "0 0 0 1000px white inset");
            }, 500);
            $("#addUserType").on("change", function () {
                $("#userProp").val(0);
                $("#idNumSpan").text("营业执照:");
                $("#addNewIdNum").val("");
            })
            $("#userProp").on("change", function (e) {
                var dtype = $(e.currentTarget).val();
                $("#idNumSpan").text((dtype == 0) ? "身份证号:" : "营业执照:");
                $("#addNewIdNum").val("");
            })
            $("#saveUserBtn").on("click", function (e) {
                var tarBtn = $(e.currentTarget);
                var param = {
                    dtype: $("#addUserType").val(),
                    user_type: $("#userProp").val(),
                    nickname: $.trim($("#tenantName").val()),
                    mobile: $("#addNewTel").val(),
                    address: $.trim($("#addNewAddr").val()),
                    id_card: $.trim($("#addNewIdNum").val()),
                    password: $.trim($("#addNewPwd").val()),
                };
                var warnIdCard = (param["dtype"] == 0) ? "身份证号不为空！" : "营业执照不为空！";
                if (!param["nickname"]) return STip("fail", "用户名不为空！");
                if (!param["password"]) return STip("fail", "密码不为空！");
                if (!regTel.test(param["mobile"])) return STip("fail", "请输入11位手机号！");
                if (!param["id_card"]) return STip("fail", warnIdCard);
                if (!param["address"]) return STip("fail", "联系地址不为空！");
                ZFT.Util.Ajax("/r/member_add", {
                    type: "POST",
                    dataType: "json",
                    params: param,
                    loading: function (res) {
                        tarBtn.removeClass("m-btn_primary").attr("disabled", "disabled");
                    },
                    success: function (res) {
                        if (res.code == 200) {
                            STip("success", res.msg);
                            $("#infoBox,#addUserBox").html("");
                        } else {
                            tarBtn.addClass("m-btn_primary").removeAttr("disabled");
                            return STip("fail", res.msg);
                        }
                    }
                })
            })
        });
    }

})
$(function () {
    new Main();
})